package com.example.coursehub.controller;

import java.util.List;

import com.example.coursehub.entity.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.example.coursehub.dto.*;
import com.example.coursehub.service.ExerciseService;

@RestController
@RequestMapping("/api/exercises")
public class ExerciseController {
    
    private final ExerciseService exerciseService;

    public ExerciseController(ExerciseService exerciseService) {
        this.exerciseService = exerciseService;
    }
    // ---------------------- 练习管理 ----------------------

    /**
     * 创建练习
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Exercise createExercise(@RequestBody ExerciseCreateDTO dto) {
        return exerciseService.createExerciseWithQuestions(dto);
    }

    /**
     * 删除练习
     */
    @PostMapping("/{exerciseId}")
    public void deleteExercise(@PathVariable String exerciseId) {
        exerciseService.deleteExercise(exerciseId);
    }

    /**
     * 根据 ID 获取练习详情
     */
    @GetMapping("/{exerciseId}")
    public Exercise getExerciseById(@PathVariable String exerciseId) {
        return exerciseService.getExerciseById(exerciseId);
    }

    // ---------------------- 练习查询 ----------------------

    /**
     * 获取课程下所有练习
     */
    @GetMapping("/course/{courseId}")
    public List<Exercise> getAllCourseExercises(@PathVariable String courseId) {
        return exerciseService.getAllCourseExercises(courseId);
    }

    /**
     * 获取用户未完成的练习（按课程）
     */
    @GetMapping("/unfinished")
    public List<Exercise> getUnfinishedExercises(
            @RequestParam String courseId,
            @RequestParam String userId) {
        return exerciseService.getUnfinishedExercises(courseId, userId);
    }

    /**
     * 获取用户已完成的练习（按课程）
     */
    @GetMapping("/finished")
    public List<Exercise> getFinishedExercises(
            @RequestParam String courseId,
            @RequestParam String userId) {
        return exerciseService.getFinishedExercises(courseId, userId);
    }

    @GetMapping("/{exerciseId}/detail")
    public ExerciseDetailDTO getExerciseDetail(
            @PathVariable String exerciseId,
            @RequestParam String userId) {
        return exerciseService.getExerciseDetail(exerciseId, userId);
    }

    // ---------------------- 题目与答案管理 ----------------------

    /**
     * 获取练习下的所有题目
     */
    @GetMapping("/{exerciseId}/questions")
    public List<Question> getExerciseQuestions(@PathVariable String exerciseId) {
        return exerciseService.getExerciseQuestions(exerciseId);
    }
        /**
     * 获取学生练习结果（含答案和得分）
     */

    // ---------------------- 收藏与错题管理 ----------------------

    /**
     * 添加收藏题目
     */
    @PostMapping("/favorite")
    public void addFavoriteQuestion(
            @RequestParam String userId,
            @RequestParam String courseId,
            @RequestParam String questionId) {
        exerciseService.addFavoriteQuestion(userId, courseId, questionId);
    }

    /**
     * 移除收藏题目
     */
    @PostMapping("/unfavorite")
    public void removeFavoriteQuestion(
            @RequestParam String userId,
            @RequestParam String courseId,
            @RequestParam String questionId) {
        exerciseService.removeFavoriteQuestion(userId, courseId, questionId);
    }

    /**
     * 获取收藏题目列表（按用户和课程）
     */
    @GetMapping("/favorite")
    public List<Question> getFavoriteQuestionBank(
            @RequestParam String userId,
            @RequestParam String courseId) {
        System.out.println("到达Controller层");
        return exerciseService.getFavoriteQuestionBank(userId, courseId);
    }

    /**
     * 获取错题集（按用户和课程）
     */
    @GetMapping("/wrong")
    public List<Question> getWrongQuestionBank(
            @RequestParam String userId,
            @RequestParam String courseId) {
        System.out.println("wrong到达Controller层");
        return exerciseService.getWrongQuestionBank(userId, courseId);
    }

    // ---------------------- 学生练习与答案 ----------------------
    public static class SubmissionRequest {
        private StudentExercise studentExercise;
        private List<StudentQuestionAnswer> studentQuestionAnswers;

        public StudentExercise getStudentExercise() {
            return studentExercise;
        }

        public void setStudentExercise(StudentExercise studentExercise) {
            this.studentExercise = studentExercise;
        }

        public List<StudentQuestionAnswer> getStudentQuestionAnswers() {
            return studentQuestionAnswers;
        }

        public void setStudentQuestionAnswers(List<StudentQuestionAnswer> studentQuestionAnswers) {
            this.studentQuestionAnswers = studentQuestionAnswers;
        }
    }
    /**
     * 提交练习及答案
     */
    @PostMapping("/submitted")
    @ResponseStatus(HttpStatus.OK)
    public void submittedExercise(@RequestBody SubmissionRequest request) {
        // 移除日志调用
        exerciseService.submittedExercise(
            request.getStudentExercise(),
            request.getStudentQuestionAnswers()
        );
    }


    /**
     * 获取练习下的所有学生练习记录
     */
    @GetMapping("/{exerciseId}/student-exercises")
    public List<StudentExercise> getAllStudentExercise(@PathVariable String exerciseId) {
        return exerciseService.getAllStudentExercise(exerciseId);
    }

    /**
     * 获取学生在某练习中的所有答案
     */
    @GetMapping("/{exerciseId}/student-answers")
    public List<StudentQuestionAnswer> getAllStudentQuestionAnswer(
            @PathVariable String exerciseId,
            @RequestParam String studentId) {
        return exerciseService.getAllStudentQuestionAnswer(exerciseId, studentId);
    }    // ---------------------- 批改功能 ----------------------

    /**
     * 获取班级待批改的练习列表
     */
    @GetMapping("/classes/{classesId}/grading")
    public List<StudentExerciseWithDetailsDTO> getClassExercisesForGrading(@PathVariable String classesId) {
        return exerciseService.getClassExercisesForGrading(classesId);
    }

    /**
     * 获取学生练习详情（用于批改）
     */
    @GetMapping("/{exerciseId}/grading/{studentId}")
    public ExerciseDetailDTO getStudentExerciseForGrading(
            @PathVariable String exerciseId,
            @PathVariable String studentId) {
        return exerciseService.getStudentExerciseForGrading(exerciseId, studentId);
    }

    /**
     * 提交批改结果
     */
    @PostMapping("/grading/submit")
    @ResponseStatus(HttpStatus.OK)
    public void submitGrades(@RequestBody GradeSubmissionDTO gradeSubmission) {
        exerciseService.submitGrades(gradeSubmission);
    }

    /**
     * 级联删除练习（含题目、答案、收藏等）
     */
    @PostMapping("/cascade/{exerciseId}")
    public void cascadeDeleteExercise(@PathVariable String exerciseId) {
        exerciseService.deleteExerciseWithCascade(exerciseId);
    }

    /**
     * 获取班级下所有练习
     */
    @GetMapping("/class/{classId}")
    public List<Exercise> getClassExercises(@PathVariable String classId) {
        System.out.println("接收到请求，classId = " + classId);
        List<Exercise> exercises = exerciseService.getAllClassExercises(classId);
        System.out.println("返回练习数量：" + (exercises != null ? exercises.size() : 0));
        return exercises;
    }

    // 加载课程题库题目
    @GetMapping("/bank/{courseId}/questions")
    public List<Question> loadCourseQuestions(@PathVariable String courseId) {
        return exerciseService.loadCourseQuestionBank(courseId);
    }

    // 添加题目到课程题库
    @PostMapping("/bank/{courseId}/questions")
    public Question addQuestionToBank(
            @PathVariable String courseId,
            @RequestBody Question question) {
        return exerciseService.addQuestionToCourseBank(question, courseId);
    }

    // 从课程题库删除题目
    @PostMapping("/bank/{courseId}/questions/{questionId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteQuestionFromBank(
            @PathVariable String courseId,
            @PathVariable String questionId) {
        exerciseService.deleteQuestionFromCourseBank(questionId, courseId);
    }
    /**
     * 计算学生在指定练习下的排名
     * @return 学生排名（从1开始）
     */
    @PostMapping("/{exerciseId}/ranking/{userId}")
    @ResponseStatus(HttpStatus.OK)
    public int calculateStudentRank(@RequestBody StudentExercise studentExercise) {
        // 调用排名计算方法
        return exerciseService.calculateStudentRank(studentExercise);
    }

    // ====================== 新增API 1：获取班级ID ======================
    /**
     * 根据课程ID和用户ID获取班级ID
     * @param courseId 课程ID（示例：C001）
     * @param userId 用户ID（示例：U003）
     * @return 匹配的班级ID（如存在）或null
     */
    @GetMapping("/classes-id")
    @ResponseStatus(HttpStatus.OK)
    public String getClassesIdByCourseAndUser(
            @RequestParam String courseId,
            @RequestParam String userId) {
        return exerciseService.getClassesIdByCourseAndUser(courseId, userId);
    }

    // ====================== 新增API 2：获取用户身份 ======================
    /**
     * 根据课程ID和用户ID获取用户身份（学生/教师/undefined）
     * @param courseId 课程ID（示例：C001）
     * @param userId 用户ID（示例：U003）
     * @return 身份标识（"student"/"teacher"/"undefined"）
     */
    @GetMapping("/role")
    @ResponseStatus(HttpStatus.OK)
    public String getUserRoleByCourseAndUser(
            @RequestParam String courseId,
            @RequestParam String userId) {
        return exerciseService.getUserRoleByCourseAndUser(courseId, userId);
    }
    // ====================== 新增API：查询用户作为教师的班级 ======================
    /**
     * 根据课程ID和用户ID查询该用户作为教师的所有班级
     * @param courseId 课程ID（示例：C001）
     * @param userId 用户ID（示例：U003）
     * @return 符合条件的班级列表
     */
    @GetMapping("/classes/teacher")
    @ResponseStatus(HttpStatus.OK)
    public List<Classes> getClassesAsTeacher(
            @RequestParam String courseId,
            @RequestParam String userId) {
        return exerciseService.getClassesAsTeacher(courseId, userId);
    }
}
